<?php
/**
 * Controller for the User-Model
 *
 * PHP versions 4 and 5
 *
 * TutoriumBase (http://tutoriumbase.my-reality.de)
 * Copyright 2012, Miguel Gonzalez (http://my-reality.de)
 *
 *
 * @copyright     Copyright 2012, Miguel Gonzalez (http://my-reality.de)
 * @link          http://tutoriumbase.my-reality.de TutoriumBase
 * @since         TutoriumBase v 0.1
 */

class UsersController extends AppController {
    
    var $name = 'Users';
    
    /**
     * Show all users
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function index() {        
        // Set title
        $this->setPageTitle('Benutzerübersicht');         
    }
    
    
    
    /**
     * Edit user with the given id
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function edit($id) {        
        $this->User->id = $id;
        
        // Only owner has access
        if (!$this->isCurrentUser($this->User->read())) {
            // No access -> redirect
            $this->redirect(array('controller' => 'tutorials', 'action' => 'index'));
        }
        
        $this->set('caption', 'Profil bearbeiten');
        
        if (!empty($this->data)) {
            // Customize password (SHA)
            if ($this->data['User']['password'] == $this->Auth->password($this->data['User']['re_password'])) {                 
                 $this->data['User']['re_password'] = $this->Auth->password($this->data['User']['re_password']);
            }
            
            // Sanitize data
            Sanitize::html($this->data, array('remove' => true));
            
            // Save data
            if ($this->User->save($this->data)) {
                $this->flashMessage('Ihr Profil wurde erfolgreich aktualisiert.', 'success'); 
                
                // Update session
                $this->Session->write('Auth', $this->User->read());
                
                $this->redirect(array(
                     'controller' => 'users', 
                     'action' => 'view/' . $this->data['User']['id'])
                );
            } else {
                // Clean password
                $this->data['User']['password'] = '';
                $this->data['User']['re_password'] = '';
                $this->flashMessage('Es ist ein oder mehrere Fehler aufgetreten!', 'fail'); 
            }
        } else {
            // Clean password
            $this->data = $this->User->read();
            $this->data['User']['password'] = '';
            $this->data['User']['re_password'] = '';
        }
        
        // Set title     
        $this->setPageTitle('Benutzer bearbeiten');
    }
    
    
    
    
    /**
     * View user with the given id
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function view($id) {        
        $this->User->id = $id;
        $user = $this->User->read();
        
        if (empty($user)) {
            // No data -> redirect
            $this->redirect(array(
                 'controller' => 'tutorials', 
                 'action' => 'index')
            );
        }
        
        // Set title
        $this->setPageTitle('Profil von ' . $user['User']['username']);

        // Find tutorial data
        $data = $this->User->Tutorial->findAllByUserId($id);
        $data = Set::sort($data, '{n}.inner_order', 'asc');
       
        // Searching for categories
        for ($i = 0; $i != count($data); ++$i) {
            foreach ($data[$i]['CategoryCount'] as $catcount) {
                $data[$i]['Category'][] = $this->User->Tutorial->CategoryCount->Category->findById($catcount['category_id']);
            }
        }
       
        // Set data
        $this->set('current_user', $user);
        $this->set('data', $data);
    }
    
    
    
    
    /**
     * Delete user with the given id
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function delete($id) {
        $this->User->id = $id;        
        $user = $this->User->read();
        
        if (empty($user))
        {
            // No data -> redirect
            $this->redirect(array(
                 'controller' => 'tutorials', 
                 'action' => 'index')
            );
        }
        
        // Delete all data of the user (Including all chapters, comments and tutorials)
        if ($user['User']['delete_all']) {
            foreach ($user['Tutorial'] as $tutorial) {
                $categories = $this->User->Tutorial->CategoryCount->findAllByTutorialId($tutorial['id']);                
                foreach ($categories as $category) {
                    $this->User->Tutorial->CategoryCount->delete($category['CategoryCount']['id']);
                }
                
                // Delete tutorial
                $this->User->Tutorial->delete($tutorial['id']);
            }
        }
        
        // Logout current user
        $this->Auth->logout();
        
        // Delete user
        if ($this->User->delete($id))
        {       
            $this->flashMessage('Ihr Account wurde erfolgreich gelöscht.', 'success');
            $this->redirect(array(
                 'controller' => 'tutorials', 
                 'action' => 'index')
            );
        }
       
       $this->redirect($this->referer());
    }
    
    
    
    
    
    /**
     * Login the current user
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function login() {        
       if (!empty($this->data)) {
           // Auth login
           if (!$this->Auth->login($this->data)) {
               if ($this->Session->read('Message.auth.message')) {
                   $this->flashMessage($this->Session->read('Message.auth.message'), 'fail');                   
               } else {
                   $this->flashMessage('Anmeldung fehlgeschlagen!', 'fail');
               }              
               $this->data['User']['username'] = '';
               $this->data['User']['password'] = '';
           } else {
               $this->flashMessage('Anmeldung erfolgreich!', 'success');
               $this->personalPage();
           }
       } 
       
       // Set data
       $this->set('caption', 'Anmeldung');
       $this->setPageTitle('Anmeldung');
    }
    
    
    
    
    
    /**
     * Login the current user
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function logout() {
        $this->Auth->logout();
        $this->flashMessage('Sie haben sich erfolgreich abgemeldet.', 'success');
        $this->redirect(array('controller' => 'tutorials', 'action' => 'index'));
    }
    
    
    
    
    /**
     * Register an user
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function register() {        
        // Titel setzen        
        $this->set('caption', 'Registrierung');
         if (!empty($this->data)) {            
            if ($this->data['User']['password'] == $this->Auth->password($this->data['User']['re_password'])) {                 
                 $this->data['User']['re_password'] = $this->Auth->password($this->data['User']['re_password']);
            }
             
            // Default image
            $this->data['User']['avatar'] = 'default.png';
            
            // Default: delete all data on user erase
            $this->data['User']['delete_all'] = false;
            
            // Sanitize           
            $this->data['User']['username'] = Sanitize::html($this->data['User']['username'], array('remove' => true));
            $this->data['User']['username'] = Sanitize::html($this->data['User']['username'], array('remove' => true));
            
            // Save user
            if ($this->User->save($this->data)) {   
                $this->flashMessage('Ihr Account wurde erfolgreich erstellt. Sie können sich jetzt anmelden.', 'success'); 
                $this->redirect(array(
                     'controller' => 'users',
                     'action' => 'login')
                );
            } else {
                $this->flashMessage('Es ist ein oder mehrere Fehler aufgetreten!', 'fail'); 
                $this->data['User']['password'] = '';
                $this->data['User']['re_password'] = '';
            }
        }
        
        $this->setPageTitle('Registrierung');
    }
    
    
    
    
    
    /**
     * Change the avatar of the user with given id
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.2
     */
    function change_avatar($id) {
        $this->User->id = $id;
        $user = $this->User->read();
        
        if (empty($user)) {
            // Empty data -> redirect
            $this->redirect(array('controller' => 'tutorials', 'action' => 'index'));
        }
        
        if(!empty($this->data)) {
            // Change image
        } 
        
        // Set data
        $this->User->id = $id;        
        $this->set('caption', 'Avatar aendern');
        $this->set('user', $user['User']);
    }
}
?>
